using System.Net;
using System.Text;
using HttpClient;

namespace Aurora.HttpClient;

/// <summary>
///webrequest http 请求工厂  只做后台任务使用
/// </summary>
public class HttpFactory
{
    private static int timeOut = 1000 * 10;
    /// <summary>
    /// post 请求 
    /// </summary>
    /// <param name="url">请求地址</param>
    /// <param name="data">数据</param>
    /// <returns></returns>
    public static T Post<T>(string url, object data, string token = null)
    {
        if (url.ToLower().StartsWith("https"))
        {
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
        }

        string value = data == null ? "" : ObjectExtension.Serialize(data);
        byte[] bs = Encoding.UTF8.GetBytes(value);
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = WebRequestMethods.Http.Post;
        request.ContentType = "application/json";
        request.ContentLength = bs.Length;
        using (Stream stream = request.GetRequestStream())
        {
            stream.Write(bs, 0, bs.Length);
        }
        if (!string.IsNullOrEmpty(token))
        {
            request.Headers.Add("Authorization", token);
        }
        request.Timeout =timeOut;
        object result = null;
        using (WebResponse response = request.GetResponse())
        {
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                string resultString = reader.ReadToEnd();
                if (typeof(T).Equals(typeof(string)))
                {
                    result = resultString;
                }
                else
                {
                    result = ObjectExtension.DeserializeObject<T>(resultString);
                }
            }

            response.Close();
            response.Dispose();
        }

        return (T)result;
    }

    /// <summary>
    /// post 请求 
    /// </summary>
    /// <param name="url">请求地址</param>
    /// <param name="data">数据</param>
    /// <returns></returns>
    public static bool PostWithoutData(string url, object data)
    {
        if (url.ToLower().StartsWith("https"))
        {
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
        }

        string value = data == null ? "" : ObjectExtension.Serialize(data);
        byte[] bs = Encoding.UTF8.GetBytes(value);
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = WebRequestMethods.Http.Post;
        request.ContentType = "application/json";
        request.ContentLength = bs.Length;
        using (Stream stream = request.GetRequestStream())
        {
            stream.Write(bs, 0, bs.Length);
        }
        request.Timeout =timeOut;
        bool result = false;

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            var code = response.StatusCode;
            result = code.Equals(HttpStatusCode.OK);
            response.Close();
            response.Dispose();
        }

        return result;
    }

    /// <summary>
    /// post 异步请求 
    /// </summary>
    /// <param name="url">请求地址</param>
    /// <param name="data">数据</param>
    /// <returns></returns>
    public static async Task<T> PostAsync<T>(string url, object data, string token = null, string contentType = null)
    {
        if (url.ToLower().StartsWith("https"))
        {
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
        }

        string value = data == null ? "" : ObjectExtension.Serialize(data);
        byte[] bs = Encoding.UTF8.GetBytes(value);
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = WebRequestMethods.Http.Post;
        if (string.IsNullOrEmpty(contentType))
        {
            request.ContentType = "application/json";
        }
        else
        {
            request.ContentType = contentType;
        }

        request.ContentLength = bs.Length;
        using (Stream stream = request.GetRequestStream())
        {
            stream.Write(bs, 0, bs.Length);
        }

        if (!string.IsNullOrEmpty(token))
        {
            request.Headers.Add("Authorization", token);
        }
        request.Timeout =timeOut;
        object result = null;
        using (WebResponse response = await request.GetResponseAsync())
        {
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                string resultString = reader.ReadToEnd();
                if (typeof(T).Equals(typeof(string)))
                {
                    result = resultString;
                }
                else
                {
                    result = ObjectExtension.DeserializeObject<T>(resultString);
                }
            }

            response.Close();
            response.Dispose();
        }

        return (T)result;
    }


    /// <summary>
    /// post 异步请求 
    /// </summary>
    /// <param name="url">请求地址</param>
    /// <param name="data">数据</param>
    /// <returns></returns>
    public static async Task<T> PostByStringAsync<T>(string url, string data, string contentType = null)
    {
        if (url.ToLower().StartsWith("https"))
        {
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
        }

        string value = data;
        byte[] bs = Encoding.UTF8.GetBytes(value);
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = WebRequestMethods.Http.Post;
        if (string.IsNullOrEmpty(contentType))
        {
            request.ContentType = "application/json";
        }
        else
        {
            request.ContentType = contentType;
        }

        request.ContentLength = bs.Length;
        using (Stream stream = request.GetRequestStream())
        {
            stream.Write(bs, 0, bs.Length);
        }
        request.Timeout =timeOut;
        object result = null;
        using (WebResponse response = await request.GetResponseAsync())
        {
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                string resultString = reader.ReadToEnd();
                if (typeof(T).Equals(typeof(string)))
                {
                    result = resultString;
                }
                else
                {
                    result = ObjectExtension.DeserializeObject<T>(resultString);
                }
            }

            response.Close();
            response.Dispose();
        }

        return (T)result;
    }

    /// <summary>
    /// GetAsync 异步请求 
    /// </summary>
    /// <param name="url">请求地址</param>
    /// <param name="data">数据</param>
    /// <returns></returns>
    public static async Task<T> GetAsync<T>(string url)
    {
        if (url.ToLower().StartsWith("https"))
        {
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
        }
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.Method = WebRequestMethods.Http.Get;
        request.ContentType = "application/json";
        request.Timeout =timeOut;
        request.Headers.Add("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36");
        object result = null;
        using (WebResponse response = await request.GetResponseAsync())
        {
            using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                string resultString = reader.ReadToEnd();
                if (typeof(T).Equals(typeof(string)))
                {
                    result = resultString;
                }
                else
                {
                    result = ObjectExtension.DeserializeObject<T>(resultString);
                }
            }

            response.Close();
            response.Dispose();
        }

        return (T)result;
    }
}